package main

import (
	"flag"
	"log"
	"net/http"
	"os"
	"path"
)

func NotFound(w http.ResponseWriter, r *http.Request) {
	log.Printf("404 not found")
	http.ServeFile(w, r, "dist/index.html")
}

func FileServerWithCustom404(fs http.FileSystem) http.Handler {
	fsh := http.FileServer(fs)
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, err := fs.Open(path.Clean(r.URL.Path))
		if os.IsNotExist(err) {
			NotFound(w, r)
			return
		}
		fsh.ServeHTTP(w, r)
	})
}

func main() {
	port := flag.String("p", "8000", "port to serve on")
	directory := flag.String("d", ".", "the directory of static file to host")
	flag.Parse()

	log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
	err := http.ListenAndServe(":"+*port, FileServerWithCustom404(http.Dir(*directory)))
	if err != nil {
		log.Fatal("ListenAndServe fail:", err)
	}
}
